package com.warm.orm.domain.job;

import cn.hutool.core.date.DateUtil;
import com.easy.query.core.annotation.Column;
import com.easy.query.core.annotation.EntityProxy;
import com.easy.query.core.annotation.Table;
import com.easy.query.core.proxy.ProxyEntityAvailable;
import com.warm.core.annotation.Excel;
import com.warm.core.constant.ScheduleConstants;
import com.warm.core.utils.StringUtils;
import com.warm.orm.domain.BaseEntity;
import com.warm.orm.domain.job.proxy.SysJobProxy;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.Size;
import org.quartz.CronExpression;

import java.io.Serial;
import java.text.ParseException;
import java.util.Date;

/**
 * 定时任务调度表 sys_job
 *
 * @author hh
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Table("sys_job")
@EntityProxy
public class SysJob extends BaseEntity implements ProxyEntityAvailable<SysJob, SysJobProxy> {
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 任务ID
     */
    @Excel(name = "任务序号", cellType = Excel.ColumnType.NUMERIC)
    @Column(primaryKey = true, increment = true)
    private Long jobId;

    private String tenantId;

    /**
     * 任务名称
     */
    @Excel(name = "任务名称")
    @NotBlank(message = "任务名称不能为空")
    @Size(max = 64, message = "任务名称不能超过64个字符")
    @Column(primaryKey = true)
    private String jobName;

    /**
     * 任务组名
     */
    @Excel(name = "任务组名")
    @Column(primaryKey = true)
    private String jobGroup;

    /**
     * 调用目标字符串
     */
    @Excel(name = "调用目标字符串")
    @NotBlank(message = "调用目标字符串不能为空")
    @Size(max = 500, message = "调用目标字符串长度不能超过500个字符")
    private String invokeTarget;

    /**
     * cron执行表达式
     */
    @Excel(name = "执行表达式 ")
    @NotBlank(message = "Cron执行表达式不能为空")
    @Size(max = 255, message = "Cron执行表达式不能超过255个字符")
    private String cronExpression;

    /**
     * cron计划策略
     */
    @Excel(name = "计划策略 ", readConverterExp = "0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行")
    private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT;

    /**
     * 是否并发执行（0允许 1禁止）
     */
    @Excel(name = "并发执行", readConverterExp = "0=允许,1=禁止")
    private String concurrent;

    /**
     * 任务状态（0正常 1暂停）
     */
    @Excel(name = "任务状态", readConverterExp = "0=正常,1=暂停")
    private String status;

    /**
     * 备注
     */
    private String remark;

    public String getNextValidTime() {
        if (StringUtils.isNotEmpty(cronExpression)) {
            return DateUtil.formatDateTime(getNextExecution(cronExpression));
        }
        return null;
    }

    /**
     * 返回下一个执行时间根据给定的Cron表达式
     *
     * @param cronExpression Cron表达式
     * @return Date 下次Cron表达式执行时间
     */
    public static Date getNextExecution(String cronExpression) {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }


    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
                .append("jobId", getJobId())
                .append("jobName", getJobName())
                .append("jobGroup", getJobGroup())
                .append("cronExpression", getCronExpression())
                .append("nextValidTime", getNextValidTime())
                .append("misfirePolicy", getMisfirePolicy())
                .append("concurrent", getConcurrent())
                .append("status", getStatus())
                .append("createBy", getCreateBy())
                .append("createTime", getCreateTime())
                .append("updateBy", getUpdateBy())
                .append("updateTime", getUpdateTime())
                .append("remark", getRemark())
                .toString();
    }

    @Override
    public Class<SysJobProxy> proxyTableClass() {
        return SysJobProxy.class;
    }
}
